from flask import Flask, request, jsonify
from flask_cors import CORS
import xgboost as xgb
import numpy as np
import pandas as pd
import json
import jieba
from datetime import datetime
from util import *

app = Flask(__name__, static_url_path="/static")
# CORS(app)  # 在这里添加 CORS
# 加载数据和模型
with open("User_state.json", "r", encoding="utf-8") as f:
    user_state: dict = json.load(f)
with open("word_count_data.json", "r", encoding="utf-8") as f:
    word_data: dict = json.load(f)

model = xgb.Booster()
model.load_model("model.bin")


@app.route("/")
def index():
    return app.send_static_file("predict_2.html")  # 返回预测页面


@app.route("/predict", methods=["POST"])
def predict():
    data = request.json

    app.logger.info(
        "Received prediction request with data: %s", data
    )  # 打印接收到的请求数据

    uid = data["uid"]
    time = data["time"]
    content = data["content"]
    input_type = data["input_type"]

    # 预处理
    # 数据: day_span_1,day_span_2,day_span_3,day_span_4,day_span_5,holiday,comment_f_min,comment_f_max,comment_f_median,comment_f_std,comment_f_mean,comment_c_min,comment_c_max,comment_c_median,comment_c_std,comment_c_mean,comment_l_min,comment_l_max,comment_l_median,comment_l_std,comment_l_mean
    time_obj = datetime.strptime(time, "%Y-%m-%d %H:%M:%S")
    weekday = time_obj.weekday()
    hour = time_obj.hour

    day_span = hour_cut(hour)
    isholiday = holiday(weekday)

    c_data = content_data(word_data, content)

    if input_type == "json":
        json_data = json.loads(data["jsonContent"])
        u_data = user_data_from_json(json_data=json_data)
    else:  # input_type == "uid":
        u_data = user_data(user_state, uid).values()

    print(u_data)
    predict_data = []
    predict_data.extend(day_span)
    predict_data.append(isholiday)
    predict_data.extend(c_data)
    predict_data.extend(u_data)

    dtest = xgb.DMatrix([predict_data])
    predicts = model.predict(dtest)
    forward_count = round_and_none_neg(predicts[0][0])
    comment_count = round_and_none_neg(predicts[0][1])
    like_count = round_and_none_neg(predicts[0][2])

    return jsonify(
        {
            "forward_count": forward_count,
            "comment_count": comment_count,
            "like_count": like_count,
        }
    )


if __name__ == "__main__":
    app.run(debug=True)


## uid 992c8c9e17aaa42c64178ef0ee28454f
## time 2015-02-14 23:42:23
## content 我用电脑20多年了，从来没有见过谁真的因为写代码机器搞不定的（编译慢也往往不是大问题）而换机器的，都TMD的是为了娱乐原因，主要是游戏之类的升级机器。所以，别动不动问这个电脑能不能写代码，那个代码能不能写代码，小霸王学习机、文曲星都可以写代码，现在随便一个电脑都是几万倍快。
